package com.hkts.beltweigher.config;


import com.hkts.beltweigher.Exception.BlankException;
import com.hkts.beltweigher.Exception.LoginFailLimitException;
import com.hkts.beltweigher.master.entity.User;
import com.hkts.beltweigher.master.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private IUserService iUserService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User hontUserByUserName = null;
        hontUserByUserName= iUserService.getUserByUserName(username);
        if(hontUserByUserName==null){
            throw new InternalAuthenticationServiceException("用户名不存在！");
        }
        if (hontUserByUserName.getStatus().equals("-1")) {
            throw new BlankException("已拉黑！");
        }
        String flagKey = "loginFailFlag:" + username;
        String value = redisTemplate.opsForValue().get(flagKey);
        Long timeRest = redisTemplate.getExpire(flagKey, TimeUnit.MINUTES);
        if (StringUtils.isNotBlank(value)) {
            //超过限制次数
            throw new LoginFailLimitException("登录错误次数超过限制，请" + timeRest + "分钟后再试");
        }
        return new SecurityUserDetails(hontUserByUserName);
    }
}
